package com.hx78.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class Mutex implements Lock {

    /**
     * 可根据自己的需要实现（tryAcquire，tryRelease）/（tryAcquireShared，tryReleaseShared）
     */
    private static class Sync extends AbstractQueuedSynchronizer {
        // 获取排他锁
        @Override
        protected boolean tryAcquire(int arg) {
            assert arg == 1;
            if(compareAndSetState(0,1)) {
                setExclusiveOwnerThread(Thread.currentThread()); // 记录独占线程
                return true;
            }
            return false;
        }

        // 释放排他锁
        @Override
        protected boolean tryRelease(int arg) {
            assert arg == 1;
            if(isHeldExclusively()) {
                throw new IllegalMonitorStateException();
            }
            setExclusiveOwnerThread(null); // 删除独占线程
            setState(0); // 重置同步状态
            return true;
        }

        /** 判断是否当前线程是不是独占线程 */
        @Override
        protected boolean isHeldExclusively() {
            return getExclusiveOwnerThread() == Thread.currentThread();
        }

        Condition newCondition() {
            return new ConditionObject();
        }
    }

    private final Sync sync = new Sync();

    /** 获取锁，拿不到则阻塞*/
    @Override
    public void lock() {
        // 调用模版方法
        sync.acquire(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    /** 获取锁，拿不到则返回*/
    @Override
    public boolean tryLock() {
        // 调用模版方法
        return sync.tryAcquire(1);
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return sync.tryAcquireNanos(1, unit.toNanos(time));
    }

    @Override
    public void unlock() {
        // 调用模版方法
        sync.release(1);
    }

    @Override
    public Condition newCondition() {
        return sync.newCondition();
    }
}
